package com.sam.scanner.utils;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class Utils {
    static Utils instance;
    static  String TAG = "SamTam";

    public static Utils getInstance() {
        return instance = new Utils();
    }


    public static void toast(Activity context, String msg){
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context.getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });

    }
    public   void post(String url,  String jsonData, String token,HTTPCallBack callback){
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonData);
        Request.Builder builder = new Request.Builder();
        builder.url("http://39.100.11.220:8080/"+url).post(requestBody);
        if(!token.equals("")){
            builder.addHeader("token",token);
        }
        Request request = builder
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: " + e.getMessage());
                callback.Fail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.Succ(response.body().string());
                }else {
                    callback.Fail("error data");
                    Log.i(TAG,"error data");
                }
            }
        });
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }
}
